<template>
  <div class="bd1">
    <div class="menu-container">
      <my-menu></my-menu>
    </div>
    <div class="table-container">
      <el-form :inline="true" class="demo-form-inline">
        <el-form-item label="食堂名">
          <el-input v-model="search" placeholder="请输入食堂名"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="searchCanteen">查询食堂</el-button>
        </el-form-item>
      </el-form>
      <el-form :inline="true" class="demo-form-inline">
        <el-form-item label="食堂名">
          <el-input v-model="addname" placeholder="请输入食堂名"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="addCanteen">添加食堂</el-button>
        </el-form-item>
      </el-form>

      <el-table :data="currentData" style="width: 100%">
        <el-table-column
          prop="canteen_id"
          label="食堂ID"
          width="100"
        ></el-table-column>
        <el-table-column
          prop="canteen_name"
          label="食堂名字"
          width="130"
        ></el-table-column>

        <!-- 由于图片路径是相对路径，这里使用 v-if 来检查图片是否存在 -->
        <el-table-column label="照片" width="250">
          <template slot-scope="scope">
            <!-- <el-image
              style="width: 200rpx; height: 85rpx"
              :src="
                'http://114.132.216.136:8080/' +
                scope.row.canteen_photo.slice(1)
              "
            ></el-image> -->
            <div v-if="!scope.row.canteen_photo" style="text-align: center">
              <el-button type="text" @click="openPhotoDialog(null, scope.row)"
                >修改照片</el-button
              >
            </div>
            <!-- 图片加载成功时显示图片 -->
            <el-image
              v-else
              :src="
                'http://114.132.216.136:8080/' +
                scope.row.canteen_photo.slice(1)
              "
              fit="contain"
              style="width: 150px; height: 30px"
              @error="handleImageError(scope.row, true)"
            ></el-image>

            <el-dialog :visible.sync="dialogVisible">
              <el-upload
                class="avatar-uploader"
                action="https://jsonplaceholder.typicode.com/posts/"
                :show-file-list="false"
                :before-upload="beforeAvatarUpload"
                :on-change="handleFileChange"
              >
                <img v-if="imageUrl" :src="imageUrl" class="avatar" />
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </el-dialog>
          </template>
        </el-table-column>
        <el-table-column align="right">
          <template slot="header"> 操作 </template>
          <template slot-scope="scope">
            <el-button size="mini" @click="handleEdit(scope.$index, scope.row)"
              >编辑</el-button
            >
            <el-button
              size="mini"
              type="danger"
              @click="handleDelete(scope.$index, scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination-container">
        <el-pagination
          :total="totalItems"
          :page-size="pageSize"
          :current-page="currentPage"
          layout="prev, pager, next, jumper"
          @current-change="handlePageChange"
        ></el-pagination>
      </div>
    </div>
  </div>
</template>

<script>
import menu from "../components/menu.vue";
import {
  getCanteen,
  delCanteen,
  findCanteen,
  changeCanteenPhoto,
  addCanteen,
  updateCanteen,
} from "@/utils/api/canteen";
// import { response } from 'express';
// import { response } from 'express';
// import { response } from 'express';
export default {
  components: {
    "my-menu": menu,
  },
  data() {
    return {
      search: "",
      totalItems: 0, // 总条目数
      pageSize: 10, // 每页显示条目个数
      currentPage: 1, // 当前页码
      canteenData: [],
      addname: "",
      show: false,
      changename: "",
      dialogVisible: false, // 控制弹窗显示的变量
      selectedPhoto: "", // 存储被选中的照片 URL
      tableKey: 0,
      imageUrl: "",
      imgbase64: "",
      selectid: 0,
      currentData: [],
    };
  },
  methods: {
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      return isJPG && isLt2M;
    },
    handleFileChange(file, fileList) {
      // 检查文件是否为图片
      if (!file.raw.type.match("image.*")) {
        this.$message.error("只能上传图片文件");
        return;
      }

      const reader = new FileReader();
      reader.onload = (e) => {
        // 获取完整的base64字符串
        const base64StringWithPrefix = e.target.result;

        // 去除前缀data:image/jpeg;base64,
        const base64String = base64StringWithPrefix.replace(
          /^data:image\/.+;base64,/,
          ""
        );

        this.imageUrl = `data:image/jpeg;base64,${base64String}`; // 保留data URL格式
        this.handleAvatarSuccess(base64String); // 调用转换成功后的函数，传入纯净的base64字符串
      };
      reader.readAsDataURL(file.raw);
    },
    handleAvatarSuccess(base64String) {
      // 在这里处理base64字符串，例如保存到数据库或进行其他操作
      console.log("图片转换为base64成功：", base64String);
      this.imgbase64 = base64String;
      changeCanteenPhoto(this.selectid, base64String).then((response) => {
        if (response.data.code == 200) {
          this.getAllCanteen();
          this.dialogVisible = false;
        }
      });

      // 如果需要，可以在这里调用其他方法或发送请求
    },
    openPhotoDialog(photoUrl, row) {
      // 弹窗逻辑，现在你可以访问 row 来获取当行的数据
      // 如果 photoUrl 为 null，则表示图片加载失败
      this.selectid = row.canteen_id;
      this.selectedPhoto = photoUrl;
      this.dialogVisible = true;
      // 这里可以添加其他处理逻辑，比如显示修改照片的表单
    },
    handleImageError(row, showError) {
      // 更新数据以标记图片加载失败
      this.$set(row, "canteen_photo_error", showError);
    },
    open() {
      return this.$prompt("请输入食堂名称", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
      })
        .then(({ value }) => {
          this.$message({
            type: "success",
            message: "修改后的食堂名是: " + value,
          });
          this.changename = value; // 将输入的值赋给 this.changename
          return value; // 返回输入的值
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "取消输入",
          });
          // 用户可能点击了取消，这里可以返回 null 或者其他默认值
          return null;
        });
    },
    async handleEdit(index, row) {
      try {
        const changename = await this.open();
        if (changename) {
          // 更新操作
          updateCanteen(row.canteen_id, changename).then((response) => {
            if (response.data.code == 200) {
              // 重新获取食堂数据
              getCanteen().then((response) => {
                console.log(response.data);
                this.canteenData = response.data.data;
                this.totalItems = this.canteenData.length; // 设置总条目数
                const start = (this.currentPage - 1) * this.pageSize;
                const end = this.currentPage * this.pageSize;
                this.currentData = this.canteenData.slice(start, end);
              });

              // console.log("hhhhh");
            }
          });
        }
      } catch (error) {
        console.error("Error during handleEdit:", error);
        // 处理错误，例如提示用户
      }
    },
    // ... 其他方法 ...
    addCanteen() {
      addCanteen(this.addname).then((response) => {
        if (response.data.code == 200) {
          this.getAllCanteen();
        }
      });
    },
    searchCanteen() {
      // console.log(this.search);
      findCanteen(this.search).then((response) => {
        console.log(response.data);
        if (response.data.code == 500) {
          console.log("食堂不存在");
        } else if (response.data.code == 200) {
          this.canteenData = response.data.data;
          this.totalItems = this.canteenData.length; // 设置总条目数
          this.setCurrentData(); // 设置当前页数据
        }
      });
    },
    handleDelete(index, row) {
      delCanteen(row.canteen_id).then((response) => {
        if (response.data.code == 200) {
          this.getAllCanteen();
        }
      });
    },
    setCurrentData() {
      // 计算当前页的数据
      const start = (this.currentPage - 1) * this.pageSize;
      const end = this.currentPage * this.pageSize;
      this.currentData = this.canteenData.slice(start, end);
    },
    handlePageChange(newPage) {
      this.currentPage = newPage;
      this.setCurrentData(); // 更新当前页数据
    },
    getAllCanteen() {
      getCanteen().then((response) => {
        console.log(response.data);
        this.canteenData = response.data.data;
        this.totalItems = this.canteenData.length; // 设置总条目数
        this.setCurrentData(); // 设置当前页数据
      });
    },
  },
  created() {
    this.getAllCanteen();
  },
};
</script>
<style>
.bd1 {
  background-color: rgb(245, 252, 241);

  width: 100%;
  height: 781px;
  background-size: 100% 100%;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
